package com.xh.facerecognition.sdk;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.huawei.hms.mlsdk.livenessdetection.MLLivenessCapture;
import com.huawei.hms.mlsdk.livenessdetection.MLLivenessCaptureConfig;
import com.huawei.hms.mlsdk.livenessdetection.MLLivenessCaptureError;
import com.huawei.hms.mlsdk.livenessdetection.MLLivenessCaptureResult;
import com.xh.facerecognition.sdk.util.BarUtils;
import com.xh.facerecognition.sdk.util.FaceUtils;

import java.io.File;

import okhttp3.Call;

import static com.huawei.hms.mlsdk.livenessdetection.MLLivenessDetectView.DETECT_MASK;


public class FaceRecognitionActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUESTCODE = 1;
    private String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private ProgressDialog mDialog;
    private Call recognitionCall;

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.transparentBar(getWindow()); //全屏布局拉到状态栏/导航栏，透明状态栏/导航栏
        if (permission()) {
            startCaptureActivity();
        }
    }

    private void showProgress(String message) {
        if (mDialog == null) {
            mDialog = ProgressDialog.show(this, "", message);
            mDialog.setCancelable(true);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (recognitionCall != null) {
                        recognitionCall.cancel();
                    }
                }
            });
        } else {
            mDialog.setMessage(message);
        }
    }

    private void hideProgress() {
        if (!isFinishing() && mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    /**
     * 动态授权
     */
    private boolean permission() {
        boolean isPermission = true;
        for (int i = 1; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                isPermission = false;
                break;
            }
        }
        if (!isPermission) {
            //没有授权
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUESTCODE);
        }
        return isPermission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUESTCODE:
                StringBuilder text = new StringBuilder();
                boolean isPermission = true;
                for (int i = 1; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        isPermission = false;
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {//用户选择了禁止不再询问
                            if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                text.append("存储/");
                            } else if (permissions[i].equals(Manifest.permission.CAMERA)) {
                                text.append("相机/");
                            }
                        }
                    }
                }
                if (isPermission) {
                    startCaptureActivity();
                } else {
                    if (!TextUtils.isEmpty(text)) {
                        text.deleteCharAt(text.length()-1);
                        Toast.makeText(this, "请在应用权限打开 "+text+" 权限", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, "使用该功能需要存储/相机权限", Toast.LENGTH_LONG).show();
                    }

                    finish();
                }
                break;
            default:
                break;
        }
    }

    //Callback for receiving the liveness detection result.
    private MLLivenessCapture.Callback callback = new MLLivenessCapture.Callback() {
        /**
         * Liveness detection success callback.
         * @param result result
         */
        @Override
        public void onSuccess(MLLivenessCaptureResult result) {
            FaceRecognition face = FaceRecognition.getInstance();
            if (face.getConfig().isEnableLive() && !result.isLive()) {
                face.onFailure("人脸检测到非活体");
                finish();
                return;
            }
            if (result.getBitmap() == null) {
                face.onFailure("获取到的图像帧为空");
                finish();
                return;
            }
            String url = face.getConfig().getUrl();
            if (!face.getConfig().isEnableFullUrl()) {
                url += FaceUtils.RECOGNITION_URL_END;
            }
            String imagePath = FaceUtils.saveBitmapFile(FaceRecognitionActivity.this, result.getBitmap());
            recognitionCall = FaceUtils.requestRecognition(url, new File(imagePath), new FaceUtils.OnFaceCallback<String>() {
                @Override
                public void onStart() {
                    showProgress("人脸识别...");
                }

                @Override
                public void onSuccess(String data) {
                    hideProgress();
                    FaceRecognition.getInstance().onSuccess(data);
                    finish();
                }

                @Override
                public void onError(String error) {
                    hideProgress();
                    FaceRecognition.getInstance().onFailure(error);
                    finish();
                }
            });
        }

        @Override
        public void onFailure(int errorCode) {
            Log.e("FaceRecognitionSDK", "MLLivenessCapture.Callback onFailure(): errorCode="+errorCode);
            if (errorCode == MLLivenessCaptureError.USER_CANCEL) {
                finish();
                return;
            }
            String errorMsg = "未知错误:"+errorCode;
            if (errorCode == MLLivenessCaptureError.CAMERA_NO_PERMISSION) {
                errorMsg = "相机权限未开启,请先开启该权限";
            } else if (errorCode == MLLivenessCaptureError.CAMERA_START_FAILED) {
                errorMsg = "相机启动失败,请检查是否有其他应用正在使用相机";
            } else if (errorCode == MLLivenessCaptureError.DETECT_FACE_TIME_OUT) {
                errorMsg = "人脸检测超时,请在两分钟内完成检测";
            }
            FaceRecognition.getInstance().onFailure(errorMsg);
            finish();
        }
    };

    private void startCaptureActivity() {
        //Obtain liveness detection config and set detect mask and sunglasses
        MLLivenessCaptureConfig captureConfig = new MLLivenessCaptureConfig.Builder().setOptions(DETECT_MASK).build();
        // Obtains the liveness detection plug-in instance.
        MLLivenessCapture capture = MLLivenessCapture.getInstance();
        //set liveness detection config
        capture.setConfig(captureConfig);

        // Enable liveness detection.
        capture.startDetect(this, this.callback);
    }
}
